/**
 * 获取图片信息
 * @param imgSrc 图片的路径，可以是相对路径，临时文件路径，存储文件路径，网络图片路径
 * @param errorMessageMode 错误消息提示模式: 'none' | 'modal' | 'message'
 */
export function getImageInfo(imgSrc, errorMessageMode = 'message') {
	return new Promise(async (resolve, reject) => {
		if (!imgSrc) {
			resolve(null);
			return;
		}
		uni.getImageInfo({
			src: imgSrc,
			success(res) {
				// console.log('getImageInfo_success', res);
				resolve(res);
			},
			fail(e) {
				// console.log('getImageInfo_fail', e);
				if (errorMessageMode === 'modal') {
					uni.showModal({
						title: t('common.errorText'),
						content: JSON.stringify(e),
						showCancel: false
					});
				} else if (errorMessageMode === 'message') {
					uni.showToast({
						title: JSON.stringify(e),
						// duration: 2000,
						icon: 'none'
					});
				}
				reject(e);
			}
		});
	});
}

/**
 * 彩色图转成单色图
 * @param width 
 * @param height 
 * @param data 
 * @param shake 
 */
export function convertToMonoImage(width, height, data, shake) {
	let g = 0
	let e = 0

	for (let i = 0; i < data.length; i += 4) {
		data[i] = (data[i] * 0.3 + data[i + 1] * 0.59 + data[i + 2] * 0.11);
	}

	for (let y = 0; y < height; y++) {
		for (let x = 0; x < width; x++) {
			let dataOffset = (width * y + x) * 4;
			g = data[dataOffset];
			if (g >= 150) { // 灰色转黑白的阈值, 可以调整打印效果
				e = g - 255;
				setPixel(data, dataOffset, 255);
			} else {
				e = g;
				setPixel(data, dataOffset, 0);
			}

			if (!shake)
				continue;

			if (x < width - 1 && y < height - 1) {
				//右边像素处理
				data[(width * y + x + 1) * 4] += 7 * e / 16;
				//下
				data[(width * (y + 1) + x) * 4] += 5 * e / 16;
				//右下
				data[(width * (y + 1) + x + 1) * 4] += e / 16;
				//左下
				if (x > 0) {
					data[(width * (y + 1) + x - 1) * 4] += 3 * e / 16;
				}
			} else if (x == width - 1 && y < height - 1) {
				//下方像素处理
				data[(width * (y + 1) + x) * 4] += 5 * e / 16;
			} else if (x < width - 1 && y == height - 1) {
				//右边像素处理
				data[(width * y + x + 1) * 4] += 7 * e / 16;
			}
		}
	}
	return data
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
	var hexArr = Array.prototype.map.call(
		new Uint8Array(buffer),
		function(bit) {
			return ('00' + bit.toString(16)).slice(-2)
		}
	)
	return hexArr.join('');
}

// 转换为灰度
function convertToGrayscale(data) {
  let g = 0
  for (let i = 0; i < data.length; i += 4) {
    g = (data[i] * 0.3 + data[i + 1] * 0.59 + data[i + 2] * 0.11)
    data[i] = g
    data[i + 1] = g
    data[i + 2] = g
  }
  return data
}

// 设定像素
function setPixel(data, offset, value) {
  data[offset] = value;
  data[offset + 1] = value;
  data[offset + 2] = value;
}

// 调整像素
function adjustPixel(data, offset, value) {
  data[offset] += value;
}
